package com.angel.intercepter;

import com.angel.shiro.SystemAdminAuthorizingRealm;
import com.angel.utils.AdminUserUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

/***
 * http握手拦截器，可以或区域request和response
 *
 * @author Rabit
 *
 */
public class HttpHandShakeIntercepter implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
            HttpSession session = serverHttpRequest.getServletRequest().getSession();
            String sessionId=session.getId();
            SystemAdminAuthorizingRealm.Principal principal = AdminUserUtils.getPrincipal();
            if (principal!=null){
                attributes.put("employee", principal.getEmployee());
            }
            attributes.put("sessionId", sessionId);
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
            HttpSession session = serverHttpRequest.getServletRequest().getSession();
            String sessionId=session.getId();
            SystemAdminAuthorizingRealm.Principal principal = AdminUserUtils.getPrincipal();
        }
    }
}
